import 'package:base_lib/common/bloc/base_bloc.dart';
import 'package:flutter/material.dart';

///更方便的管理Bloc
class BlocProvider<B extends BaseBloc> extends StatefulWidget {
  final B bloc; //bloc

  final Widget child; //子Widget

  ///构造
  const BlocProvider({Key key, @required this.bloc, @required this.child})
      : super(key: key);

  ///通过 [context#getElementForInheritedWidgetOfExactType] 获取 bloc 实例
  static B of<B extends BaseBloc>(BuildContext context) {
    _BlocProviderInherited<B> provider = context
        .getElementForInheritedWidgetOfExactType<_BlocProviderInherited<B>>()
        ?.widget;
    return provider?.bloc;
  }

  @override
  _BlocProviderState<B> createState() {
    return _BlocProviderState();
  }
}

class _BlocProviderState<T extends BaseBloc>
    extends State<BlocProvider<BaseBloc>> {
  @override
  void initState() {
    super.initState();
    widget.bloc?.initState();
  }

  /// 便于资源的释放
  @override
  void dispose() {
    widget.bloc?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new _BlocProviderInherited<T>(
      child: widget.child,
      bloc: widget.bloc,
    );
  }
}

class _BlocProviderInherited<T> extends InheritedWidget {
  _BlocProviderInherited({
    Key key,
    @required Widget child,
    @required this.bloc,
  }) : super(key: key, child: child);

  final T bloc;

  @override
  bool updateShouldNotify(_BlocProviderInherited oldWidget) => false;
}
